rm(list = ls())

## packages 

library(tidyverse)
library(fixest)
library(grid)
library(pBrackets) 
library(broom)

## Code temporal categories

dat <- readRDS('data/civey_clean.rds') %>%
  mutate(date_month_agg = case_when(
    date_month %in% 2:4 ~ 2,
    date_month %in% 5:7 ~ 3,
    date_month %in% 8:9 ~ 4,
    date_month %in% c(1, 10:12) ~ 1  
  ))   

## Estimate event study specification

res <- feols(vote_afd ~ i(date_month_agg, freibad_in_zip, ref = 2) | user_id + date, 
             data = dat %>% filter(foreign_non_eu_share_bin == 'High'),
             cluster = ~ user_id) %>%
  broom::tidy(conf.int = T) %>%
  mutate(month = parse_number(term),
         conf.low90 = estimate - 1.645 * std.error,
         conf.high90 = estimate + 1.645 * std.error) 


## Plot 

zero_row <- data.frame(month = 2, 
                       estimate = 0) 

res <- bind_rows(res, zero_row) %>%
  mutate(summer_bin = ifelse(month >= 3, 'Outdoor pool season', 'Indoor pool season'))

month_labels <- c('1' = 'Oct-Jan',
                  '2' = 'Feb-Apr',
                  '4' = 'May-Jul',
                  '5' = 'Aug-Sep ')


p1 <- ggplot(res, aes(x = month, y = estimate, col = summer_bin, shape = summer_bin)) + 
  geom_errorbar(width = 0, aes(ymin = conf.low, ymax = conf.high)) + 
  geom_errorbar(width = 0, linewidth = .8, aes(ymin = conf.low90, ymax = conf.high90)) + 
  theme_minimal() + 
  geom_vline(xintercept = 2.5, linetype = 'dotdash') + 
  geom_hline(yintercept = 0) + 
  geom_point(shape = 21, fill = 'black', size = 2.5) + 
  labs(x = '',
       y = 'Effect on AfD\nsupport (in p.p.)',
       col = '') +
  scale_x_continuous(breaks = 1:4, labels = month_labels) +
  scale_color_grey(start = 0.8, end = 0.1) +  
  theme(legend.position = 'none') 

p1
